﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CPPEI.EBS.Domain.Services
{
    public class PublishService
    {
        public const string FIELD_APPID = "AppId";
        public const string FIELD_APPTOKEN = "AppToken";
        public const string FIELD_NAMESPACE = "Namespace";
        public const string FIELD_EVENT = "Event";
        public const string FIELD_CALLBACK = "Callback";
        public const string FIELD_DATA = "Data";

        public ServiceResult Publish(Guid appId, string appToken, string @namespace, string @event, string data)
        {
            Logger.InfoToTag(Library.LogTAG, string.Format("Publish,app:{0},token:{1},ns:{2},e:{3},data:{4}", appId, appToken, @namespace, @event, data));

            NamespaceEntry nsEntry = Storage.Get(@namespace);
            if(nsEntry ==null)
            {
                return new ServiceResult();
            }

            Dictionary<string, string> @params = new Dictionary<string, string>();
            @params.Add(FIELD_NAMESPACE, @namespace);
            @params.Add(FIELD_EVENT, @event);
            @params.Add(FIELD_DATA, data);

            List<EventEntry> eventEntries = nsEntry.Find(@event);

            for (int index = 0; index < eventEntries.Count; index++)
            {
                EventEntry eventEntry = eventEntries[index];

                Logger.InfoToTag(Library.LogTAG, string.Format("Publish-Send,app:{0},callback:{1},ns:{2},e:{3},data:{4}", eventEntry.AppId, eventEntry.Callback, @namespace, @event, data));
                try
                {
                    HttpClient.PostAsync(eventEntry.Callback, @params);
                }
                catch(Exception ex)
                {
                    Logger.ErrorToTag(Library.LogTAG, string.Format("Publish-Send,app:{0},callback:{1},ns:{2},e:{3},data:{4}出错,ex:{5}", eventEntry.AppId, eventEntry.Callback, @namespace, @event, data, ex));
                }
            }

            return new ServiceResult();
        }
    }
}
